<template>
  <div class="file-upload-container">
    <el-upload
      class="upload-demo"
      drag
      ref="uploadRef"
      :limit="1"
      :on-exceed="handleExceed"
      :action="fileServerEndpoint"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :on-remove="handleFileListRemove"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件 or <em> 点击上传 </em></div>
      <template #tip>
        <div class="el-upload__tip">文件大小不得超过50MB</div>
      </template>
    </el-upload>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { checkResult } from "@/utils/Rutil.js";
import { pdfEndpoint } from "@/api/media/file/uploadFile";

// 定义上传文件路径绑定
const uploadRef = ref();

const fileUrl = defineModel("fileUrl", {
  default: ref(""),
});
const fileServerEndpoint = pdfEndpoint;
const handleAvatarSuccess = (response, uploadFile) => {
  console.log("response", response);
  console.log("uploadFile", uploadFile);
  // 如果请求成功
  if (checkResult(response)) {
    fileUrl.value = response.data;
    ElMessage.success("上传成功");
  } else {
    ElMessage.error("上传失败");
  }
};

const beforeAvatarUpload = (rawFile) => {
  const uploadFileList = ["application/pdf"];
  // 检测上传
  let exists = uploadFileList.some((type) => type === rawFile.type);
  if (!exists) {
    ElMessage.error("仅允许pdf文件进行上传!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 50) {
    ElMessage.error("文件不得超过50MB!");
    return false;
  }
  console.log("允许上传");
  return true;
};

import { genFileId } from "element-plus";
/**
 * 超量处理机
 */
const handleExceed = (files) => {
  uploadRef.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};

const handleFileListRemove = (uploadFile, uploadFiles) => {
  console.log("handleFileListRemove", uploadFiles);
  // 如果文件列表为空
  if (uploadFiles.length === 0) {
    fileUrl.value = "";
  }
  ElMessage.success("移除上传列表成功");
};
</script>

<style lang="scss">
.file-upload-container {
  width: 100%;
}
</style>
